//index.js
//获取应用实例
const app = getApp()
const sss = require('../son/SHA-1/sha.js');
const totp = require('../son/SHA-1/totp.js');

var probable = 0;
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    username: '',
    pwd: '',
    pwd2: '',
    pwd3: '',
    animation1: {},

    isAccount: false,
    isChecked: false,
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  formsubmit: function(e) {
      var _this = this;
      if (e.detail.value.username.length == 13 && e.detail.value.pwd && e.detail.value.pwd2 && e.detail.value.pwd3) {
        _this.setData({
          username: e.detail.value.username,
          pwd: e.detail.value.pwd,
          pwd2: e.detail.value.pwd2,
          pwd3: e.detail.value.pwd3
        })
        var a =
          wx.request({
            url: 'https://api.ziqiang.net.cn/token/', //仅为示例，并非真实的接口地址
            method: "GET",
            data: {
              sid: e.detail.value.username,
              pwd_edu: e.detail.value.pwd,
              pwd_lib: e.detail.value.pwd2,
              //pwd_wifi:e.detail.value.pwd3,
              binding_type: 2
            },
            dataType: JSON,
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function(res) {
              _this.setData({
                isChecked: false,
              })

              wx.showToast({
                title: '登入成功',
                icon: 'success',
                duration: 2000,
              })
              _this.setData({
                isAccount: true,
              })
              wx.setStorage({
                key: "stdNumber",
                data: e.detail.value.username
              })
              wx.setStorage({
                key: "eduNumber",
                data: e.detail.value.pwd
              })
              wx.setStorage({
                key: "libNumber",
                data: e.detail.value.pwd2
              })
              wx.setStorage({
                key: "wifiNumber",
                data: e.detail.value.pwd3
              })
              wx.getStorage({
                key: 'stdNumber',
                success: function(res) {
                  let cache = res.data;
                  if (cache.length == 13) {
                    _this.setData({
                      isAccount: true,
                    })
                  }
                  _this.setData({
                    Account1: cache,
                  })
                },
                fail: function() {
                  _this.setData({
                    isAccount: false,
                  })
                }
              })
              wx.getStorage({
                key: 'eduNumber',
                success: function(res) {
                  let cache = res.data;
                  cache = cache.slice(0, 2);
                  cache = cache + "...";
                  _this.setData({
                    Account2: cache,
                  })
                },
                fail: function() {
                  _this.setData({
                    isAccount: false,
                  })
                }
              })
              wx.getStorage({
                key: 'libNumber',
                success: function(res) {
                  let cache = res.data;
                  cache = cache.slice(0, 2);
                  cache = cache + "...";
                  _this.setData({
                    Account3: cache,
                  })
                },
                fail: function() {
                  _this.setData({
                    isAccount: false,
                  })
                }
              })
              wx.getStorage({
                key: 'wifiNumber',
                success: function(res) {
                  let cache = res.data;
                  cache = cache.slice(0, 2);
                  cache = cache + "...";
                  _this.setData({
                    Account4: cache,
                  })
                },
                fail: function() {
                  _this.setData({
                    isAccount: false,
                  })
                }
              }) //账号数据缓存



              var data = JSON.parse(res.data);

              app.globalData.Token = data.token;
              app.globalData.sid = e.detail.value.username;
              app.globalData.pwd = e.detail.value.pwd;
              app.globalData.pwd_lib = e.detail.value.pwd2;
              app.globalData.pwd_wifi = e.detail.value.pwd3;
              var totpSECRET_KEY = sss.getEncodeString('+.a*vD@JrLYauz(M)HA^=}sh');
              var secret_key = totp.updateOtp(totpSECRET_KEY);
              //totp.getCode(totpSECRET_KEY)
              var timestamp = Math.round(new Date().getTime() / 1000);
              var timestampstr = timestamp.toString(); //获取unix时间戳字符串
              var ran = Math.ceil(Math.random() * 1000000000);
              var ranstr = ran.toString();
              var arr = new Array(3);
              arr[0] = secret_key;
              arr[1] = timestampstr;
              arr[2] = ranstr;
              arr = arr.sort(); //字典序排序
              var mix = arr[0] + arr[1] + arr[2];
              var sha1 = sss.de2(mix).toString(); //sha1算法
              var a =
                wx.request({
                  url: 'https://api.ziqiang.net.cn/courses/', //仅为示例，并非真实的接口地址
                  method: "GET",
                  data: {

                  },
                  dataType: JSON,
                  header: {
                    'content-type': 'application/json', // 默认值
                    'Authorization': 'Token ' + app.globalData.Token,
                    'x-zswd-signature': sha1,
                    'x-zswd-timestamp': timestamp,
                    'x-zswd-nonce': ran,
                  },
                  success: function(res) {

                    var data = JSON.parse(res.data);
                    app.globalData.Course_Grade = data;
                  },
                  Error: function(res) {
                    wx.showToast({
                      title: '登入失败',
                      icon: 'cancel',
                      duration: 2000,
                    })
                  }
                })
              var b =
                wx.request({
                  url: 'https://api.ziqiang.net.cn/book/borrow/current_record/', //仅为示例，并非真实的接口地址
                  method: "GET",
                  data: {

                  },
                  dataType: JSON,
                  header: {
                    'content-type': 'application/json', // 默认值
                    'Authorization': 'Token ' + app.globalData.Token,
                    'x-zswd-signature': sha1,
                    'x-zswd-timestamp': timestamp,
                    'x-zswd-nonce': ran,
                  },
                  success: function(res) {

                    var data = JSON.parse(res.data);
                    app.globalData.lend_currentRecord = data;

                  },
                  Error: function(res) {
                    wx.showToast({
                      title: '登入失败',
                      icon: 'cancel',
                      duration: 2000,
                    })
                  }
                })


              var c =
                wx.request({
                  url: 'https://api.ziqiang.net.cn/settings/?name=term_begin_date,term_now_year,term_now_semester', //仅为示例，并非真实的接口地址
                  method: "GET",
                  data: {

                  },
                  dataType: JSON,
                  header: {
                    'content-type': 'application/json', // 默认值
                    'Authorization': 'Token ' + app.globalData.Token,
                    'x-zswd-signature': sha1,
                    'x-zswd-timestamp': timestamp,
                    'x-zswd-nonce': ran,
                  },
                  success: function(res) {

                    var data = JSON.parse(res.data);
                    app.globalData.term_now_year = data.term_now_year;
                    app.globalData.term_begin_date = data.term_begin_date;
                    app.globalData.term_now_semester = data.term_now_semester-1;
                  },
                  Error: function(res) {
                    wx.showToast({
                      title: '登入失败',
                      icon: 'cancel',
                      duration: 2000,
                    })
                  }
                })

              var d =
                wx.request({
                  url: 'https://api.ziqiang.net.cn/book/borrow/history_record/', //仅为示例，并非真实的接口地址
                  method: "GET",
                  data: {

                  },
                  dataType: JSON,
                  header: {
                    'content-type': 'application/json', // 默认值
                    'Authorization': 'Token ' + app.globalData.Token,
                    'x-zswd-signature': sha1,
                    'x-zswd-timestamp': timestamp,
                    'x-zswd-nonce': ran,
                  },
                  success: function(res) {

                    var data = JSON.parse(res.data);
                    app.globalData.lend_historyRecord = data;

                  },
                  Error: function(res) {
                    wx.showToast({
                      title: '登入失败',
                      icon: 'cancel',
                      duration: 2000,
                    })
                  }
                });
              var f =
                wx.request({
                  url: 'https://api.ziqiang.net.cn/courses/gpa/normal/', //仅为示例，并非真实的接口地址
                  method: "GET",
                  data: {},
                  dataType: JSON,
                  header: {
                    'content-type': 'application/json', // 默认值
                    'Authorization': 'Token ' + app.globalData.Token,
                    'x-zswd-signature': sha1,
                    'x-zswd-timestamp': timestamp,
                    'x-zswd-nonce': ran,
                  },
                  success: function(res) {

                    var data = JSON.parse(res.data);
                    app.globalData.gpa = data.gpa;
                    app.globalData.total_credit = data.total_credit;
                    app.globalData.total_courses = data.total_courses;
                    app.globalData.average_grade = data.average_grade;
                  },
                  Error: function(res) {
                    wx.showToast({
                      title: '登入失败',
                      icon: 'cancel',
                      duration: 2000,
                    })
                  }
                });




            },
            Error: function(res) {
              wx.showToast({
                title: '登入失败',
                icon: 'cancel',
                duration: 2000,
              })
            }
          })
      } else {
        wx.showToast({
          title: '请完整输入信息',
          delay: 1000
        })
      }

    }

    ,
  onLoad: function() {

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  changeProperty: function(e) {
    var _this = this;
    probable = 0;
    wx.removeStorage({
      key: 'stdNumber',
      success: function(res) {
        probable = probable + 1;
      }
    })
    wx.removeStorage({
      key: 'eduNumber',
      success: function(res) {
        probable = probable + 1;
      }
    })
    wx.removeStorage({
      key: 'libNumber',
      success: function(res) {
        probable = probable + 1;
      }
    })
    wx.getStorage({
      key: 'stdNumber',
      fail: function(res) {
        wx.showToast({
          title: '清除数据成功，请重新登入',
          icon: 'success',
          duration: 1200
        })
        _this.setData({
          isAccount: false,
        })
      }
    })



  },
  back: function() {
    wx.navigateBack({
      url: '../index/index'
    })
  },
  onShow: function() {

    wx.setNavigationBarTitle({
      title: '掌上武大Tim'
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#00CC66',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })

    var _this = this;
    wx.getStorage({
      key: 'stdNumber',
      success: function(res) {
        let cache = res.data;
        if (cache.length == 13) {
          _this.setData({
            isAccount: true,
            sid: res.data
          })
        }
        _this.setData({
          Account1: cache,
        })
      },
      fail: function() {
        _this.setData({
          isAccount: false,
        })
      }
    })
    wx.getStorage({
      key: 'eduNumber',
      success: function(res) {
        let cache = res.data;
        cache = cache.slice(0, 2);
        cache = cache + "...";
        _this.setData({
          Account2: cache,
          pwd_edu: res.data
        })
      },
      fail: function() {
        _this.setData({
          isAccount: false,
        })
      }
    })
    wx.getStorage({
      key: 'libNumber',
      success: function(res) {
        let cache = res.data;
        cache = cache.slice(0, 2);
        cache = cache + "...";
        _this.setData({
          Account3: cache,
          pwd_lib: res.data
        })
      },
      fail: function() {
        _this.setData({
          isAccount: false,
        })
      }
    })
    wx.getStorage({
      key: 'wifiNumber',
      success: function(res) {
        let cache = res.data;
        cache = cache.slice(0, 2);
        cache = cache + "...";
        _this.setData({
          Account4: cache,
          pwd_wifi: res.data
        })
        //---------------
        if (_this.data.sid) {
          if (_this.data.sid.length == 13 && _this.data.pwd_edu && _this.data.pwd_lib && _this.data.pwd_wifi) {
            var a =
              wx.request({
                url: 'https://api.ziqiang.net.cn/token/', //仅为示例，并非真实的接口地址
                method: "GET",
                data: {
                  sid: _this.data.sid,
                  pwd_edu: _this.data.pwd_edu,
                  pwd_lib: _this.data.pwd_lib,
                  //pwd_wifi: _this.data.pwd_wifi,
                  binding_type: 2
                },
                dataType: JSON,
                header: {
                  'content-type': 'application/json' // 默认值
                },
                success: function(res) {
                  _this.setData({
                    isChecked: false,
                  })

                  _this.setData({
                    isAccount: true,
                  })

                  var data = JSON.parse(res.data);

                  app.globalData.Token = data.token;
                  app.globalData.sid = _this.data.Account1;
                  app.globalData.pwd = _this.data.Account2;
                  app.globalData.pwd_lib = _this.data.Account3;
                  app.globalData.pwd_wifi = _this.data.Account4;
                  var totpSECRET_KEY = sss.getEncodeString('+.a*vD@JrLYauz(M)HA^=}sh');
                  var secret_key = totp.updateOtp(totpSECRET_KEY);
                  //totp.getCode(totpSECRET_KEY)
                  var timestamp = Math.round(new Date().getTime() / 1000);
                  var timestampstr = timestamp.toString(); //获取unix时间戳字符串
                  var ran = Math.ceil(Math.random() * 1000000000);
                  var ranstr = ran.toString();
                  var arr = new Array(3);
                  arr[0] = secret_key;
                  arr[1] = timestampstr;
                  arr[2] = ranstr;
                  arr = arr.sort(); //字典序排序
                  var mix = arr[0] + arr[1] + arr[2];
                  var sha1 = sss.de2(mix).toString(); //sha1算法
                  var a =
                    wx.request({
                      url: 'https://api.ziqiang.net.cn/courses/', //仅为示例，并非真实的接口地址
                      method: "GET",
                      data: {

                      },
                      dataType: JSON,
                      header: {
                        'content-type': 'application/json', // 默认值
                        'Authorization': 'Token ' + app.globalData.Token,
                        'x-zswd-signature': sha1,
                        'x-zswd-timestamp': timestamp,
                        'x-zswd-nonce': ran,
                      },
                      success: function(res) {

                        var data = JSON.parse(res.data);
                        app.globalData.Course_Grade = data;
                      },
                      Error: function(res) {
                        wx.showToast({
                          title: '登入失败',
                          icon: 'cancel',
                          duration: 2000,
                        })
                      }
                    })
                  var b =
                    wx.request({
                      url: 'https://api.ziqiang.net.cn/book/borrow/current_record/', //仅为示例，并非真实的接口地址
                      method: "GET",
                      data: {

                      },
                      dataType: JSON,
                      header: {
                        'content-type': 'application/json', // 默认值
                        'Authorization': 'Token ' + app.globalData.Token,
                        'x-zswd-signature': sha1,
                        'x-zswd-timestamp': timestamp,
                        'x-zswd-nonce': ran,
                      },
                      success: function(res) {

                        var data = JSON.parse(res.data);
                        app.globalData.lend_currentRecord = data;

                      },
                      Error: function(res) {
                        wx.showToast({
                          title: '登入失败',
                          icon: 'cancel',
                          duration: 2000,
                        })
                      }
                    })


                  var c =
                    wx.request({
                      url: 'https://api.ziqiang.net.cn/settings/?name=term_begin_date,term_now_year,term_now_semester', //仅为示例，并非真实的接口地址
                      method: "GET",
                      data: {

                      },
                      dataType: JSON,
                      header: {
                        'content-type': 'application/json', // 默认值
                        'Authorization': 'Token ' + app.globalData.Token,
                        'x-zswd-signature': sha1,
                        'x-zswd-timestamp': timestamp,
                        'x-zswd-nonce': ran,
                      },
                      success: function(res) {

                        var data = JSON.parse(res.data);
                        app.globalData.term_now_year = data.term_now_year;
                        app.globalData.term_begin_date = data.term_begin_date;
                        app.globalData.term_now_semester = data.term_now_semester-1;
                      },
                      Error: function(res) {
                        wx.showToast({
                          title: '登入失败',
                          icon: 'cancel',
                          duration: 2000,
                        })
                      }
                    })

                  var d =
                    wx.request({
                      url: 'https://api.ziqiang.net.cn/book/borrow/history_record/', //仅为示例，并非真实的接口地址
                      method: "GET",
                      data: {

                      },
                      dataType: JSON,
                      header: {
                        'content-type': 'application/json', // 默认值
                        'Authorization': 'Token ' + app.globalData.Token,
                        'x-zswd-signature': sha1,
                        'x-zswd-timestamp': timestamp,
                        'x-zswd-nonce': ran,
                      },
                      success: function(res) {

                        var data = JSON.parse(res.data);
                        app.globalData.lend_historyRecord = data;

                      },
                      Error: function(res) {
                        wx.showToast({
                          title: '登入失败',
                          icon: 'cancel',
                          duration: 2000,
                        })
                      }
                    });
                  var f =
                    wx.request({
                      url: 'https://api.ziqiang.net.cn/courses/gpa/normal/', //仅为示例，并非真实的接口地址
                      method: "GET",
                      data: {},
                      dataType: JSON,
                      header: {
                        'content-type': 'application/json', // 默认值
                        'Authorization': 'Token ' + app.globalData.Token,
                        'x-zswd-signature': sha1,
                        'x-zswd-timestamp': timestamp,
                        'x-zswd-nonce': ran,
                      },
                      success: function(res) {

                        var data = JSON.parse(res.data);
                        app.globalData.gpa = data.gpa;
                        app.globalData.total_credit = data.total_credit;
                        app.globalData.total_courses = data.total_courses;
                        app.globalData.average_grade = data.average_grade;
                      },
                      Error: function(res) {
                        wx.showToast({
                          title: '登入失败',
                          icon: 'cancel',
                          duration: 2000,
                        })
                      }
                    });




                },
                Error: function(res) {
                  wx.showToast({
                    title: '登入失败',
                    icon: 'cancel',
                    duration: 2000,
                  })
                }
              })
          }
        }
        //------------------------
      },
      fail: function() {
        _this.setData({
          isAccount: false,
        })
      }
    })





    let animation1 = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 200,
      timingFunction: "ease",
      delay: 0
    });
    animation1.backgroundColor('#FFFFFF').step();
    animation1.backgroundColor('#00CC66').step();
    this.setData({
      animation1: animation1.export()
    });
  },

  modify1: function() {
    var _this = this;
    probable = 0;
    wx.removeStorage({
      key: 'stdNumber',
      success: function(res) {
        probable = probable + 1;
        wx.getStorage({
          key: 'stdNumber',
          fail: function (res) {
            wx.showToast({
              title: '清除数据成功，请重新登入',
              icon: 'success',
              duration: 1200
            })
            _this.setData({
              isAccount: false,
              username: ''
            })
          }
        })
      }
    })
    
  },
  modify2: function() {
    var _this = this;
    probable = 0;
    wx.removeStorage({
      key: 'eduNumber',
      success: function(res) {
        probable = probable + 1;
        wx.getStorage({
          key: 'eduNumber',
          fail: function (res) {
            wx.showToast({
              title: '清除数据成功，请重新登入',
              icon: 'success',
              duration: 1200
            })
            _this.setData({
              isAccount: false,
              pwd: ''
            })
          }
        })
      }
    })
    
  },
  modify3: function() {
    var _this = this;
    probable = 0;
    wx.removeStorage({
      key: 'libNumber',
      success: function(res) {
        probable = probable + 1;
        wx.getStorage({
          key: 'libNumber',
          fail: function (res) {
            wx.showToast({
              title: '清除数据成功，请重新登入',
              icon: 'success',
              duration: 1200
            })
            _this.setData({
              isAccount: false,
              pwd2: ''
            })
          }
        })
      }
    })
    
  },

  modify4: function() {
    var _this = this;
    probable = 0;
    wx.removeStorage({
      key: 'wifiNumber',
      success: function(res) {
        probable = probable + 1;
        wx.getStorage({
          key: 'wifiNumber',
          fail: function (res) {
            wx.showToast({
              title: '清除数据成功，请重新登入',
              icon: 'success',
              duration: 1200
            })
            _this.setData({
              isAccount: false,
              pwd3: ''
            })
          }
        })
      }
    })
    
  },


})